/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var moment = require("moment");
var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');

var memberController = {
    getmemberByID: function (req, res) {
        co(function () {
            var include = [{ model: seq.memberRespresentModule, attributes: ['name'] }];
            seq.memberModule.findOne({ where: req.params, include: include }).then(function (result) {
                res.json({ "success": true, "msg": "查询成功！", "result": result });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })

    },
    addMember: function (req, res) {
        var memberId = util.getUUID();
        var createTime = util.getNowTime();
        var tel = req.query.tel;
        if (util.valPhone(tel)) {
            seq.memberModule.count({ where: { tel: tel } }).then(function (memCount) {
                if (memCount == 0) {
                    //添加会员
                    req.query.id = memberId;
                    req.query.createTime = createTime;
                    req.query.filed10 = util.registerScore;

                    //添加积分
                    var integralParams = {};
                    integralParams.id = util.getUUID();
                    integralParams.createTime = util.getNowTime();
                    integralParams.memberId = memberId;
                    integralParams.jfType = 1;
                    integralParams.jfState = 1;
                    integralParams.score = util.registerScore;
                    integralParams.filed2 = req.query.openId;
                    //添加订阅
                    var nowTime = util.getNowTime();

                    var sortSubscribeLogSql = "insert into lm_sort_subscribe_log (id,member_id,open_id,item,create_time) values ";
                    for (i = 1; i <= 6; i++) {
                        sortSubscribeLogSql += "('" + util.getUUID() + "','" + memberId + "','" + req.query.openId + "','" + i + "','" + nowTime + "'),";
                    }
                    sortSubscribeLogSql = sortSubscribeLogSql.substring(0, sortSubscribeLogSql.lastIndexOf(","));
                    seq.memberModule.create(req.query).then(function (memAdd) {
                        seq.integralRecordModule.create(integralParams).then(function (integralAdd) {
                            seq.sequelize.query(sortSubscribeLogSql).spread(function (itemAdd) {
                                res.json({ 'success': true, 'msg': '恭喜你注册成功！' });
                            })
                        })
                    })
                } else {
                    res.json({ 'success': false, 'msg': '该手机号已注册！' });
                }
            })
        } else {
            res.json({ 'success': false, 'msg': '手机号格式不正确！' });
        }
    }

}
module.exports = memberController;